package com.atguigu.spzx.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.spzx.common.exception.SPZXException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.helper.MenuHelper;
import com.atguigu.spzx.mapper.SysMenuMapper;
import com.atguigu.spzx.model.entity.system.SysMenu;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.SysMenuVo;
import com.atguigu.spzx.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.awt.*;
import java.util.LinkedList;
import java.util.List;


@Service
@Transactional
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
        List<SysMenu> sysMenuList = sysMenuMapper.selectAll();
        if (CollectionUtil.isEmpty(sysMenuList)) return null;
        List<SysMenu> list = MenuHelper.buildTree(sysMenuList);
        return list;


    }

    @Override
    public void save(SysMenu sysMenu) {
        sysMenuMapper.insert(sysMenu);
    }

    @Override
    public void updateById(SysMenu sysMenu) {
        sysMenuMapper.updateById(sysMenu);
    }

    @Override
    public void removeById(Long id) {
        int count = sysMenuMapper.countByParentId(id);
        if (count > 0) {
            throw new SPZXException(ResultCodeEnum.NODE_ERROR);
        }
        sysMenuMapper.removeById(id);
    }

    @Override
    public List<SysMenuVo> findUserMenuList() {
        SysUser sysUser = (SysUser) AuthContextUtil.get();

        List<SysMenu> sysMenuList = sysMenuMapper.selectListByUserId(sysUser.getId());
        //构建树形数据
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(sysMenuList);
        // 将List<SysMenu>对象转换成List<SysMenuVo>对象
        List<SysMenuVo> sysMenuVo = this.buildMenus(sysMenuTreeList);
        return sysMenuVo;
    }

    // 将List<SysMenu>对象转换成List<SysMenuVo>对象
    private List<SysMenuVo> buildMenus(List<SysMenu> menus) {
        List<SysMenuVo> sysMenuVoList = new LinkedList<SysMenuVo>();
        for (SysMenu menu : menus) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setName(menu.getComponent());
            sysMenuVo.setTitle(menu.getTitle());
            if (!CollectionUtils.isEmpty(menu.getChildren())) {
                sysMenuVo.setChildren(buildMenus(menu.getChildren()));
            }
            sysMenuVoList.add(sysMenuVo);
        }
        return sysMenuVoList;

    }
}
